package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.media.dto.ContentDto;
import com.heima.media.dto.ImageDto;
import com.heima.media.dto.WmNewsDto;
import com.heima.media.dto.WmNewsPageDto;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmNewsMaterial;
import com.heima.media.mapper.WmNewsMapper;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsMaterialService;
import com.heima.media.service.IWmNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.*;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author Mr_Su
 * @since 2022-06-28
 */
@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {

    @Autowired
    @Lazy    // 解决循环依赖问题
    private IAuditService auditService;

    @Override
    public ResponseResult listByCondition(WmNewsPageDto dto) {
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        // 各种条件查询
        LambdaQueryWrapper<WmNews> lqwWmNews = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null) {
            lqwWmNews.eq(WmNews::getStatus, dto.getStatus());
        }
        if (dto.getChannelId() != null) {
            lqwWmNews.eq(WmNews::getChannelId, dto.getChannelId());
        }

        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            lqwWmNews.ge(WmNews::getPublishTime, dto.getBeginPubDate()).le(WmNews::getPublishTime, dto.getEndPubDate());
        }

        if (StringUtils.isNoneBlank(dto.getKeyword())) {
            lqwWmNews.like(WmNews::getTitle, dto.getKeyword());
        }

        // 隐藏条件: 当前登录用户
        lqwWmNews.eq(WmNews::getUserId, user.getUserId());
        // 排序
        lqwWmNews.orderByDesc(WmNews::getPublishTime);
        // 构建分页对象
        Page page = new Page(dto.getPage(), dto.getSize());
        this.page(page, lqwWmNews);
        return new PageResponseResult<>(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
    }

    @Override
    public ResponseResult submit(WmNewsDto dto) {
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 保存自媒体文章
        // 1. 先判断是否有id,如果有就是修改,如果没有就是新增
        if (dto.getId() != null) {
            // 删除已关联素材的关系
            deleteRelation(dto.getId());
        }

        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
//        wmNews.setType(dto.getType()); // 文章封面类型  0 无图 1 单图 3 多图 -1 自动
        wmNews.setUserId(user.getUserId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setStatus(dto.getStatus()); // 状态 提交为1  草稿为0
//        wmNews.setReason(); // 审核失败的原因,暂不处理
//        wmNews.setArticleId(); // app文章id,等审核通过后远程调用article微服务生成一个app文章,返回app文章的id,暂不处理
        List<ImageDto> coverImages = dto.getImages();
        wmNews.setImages(JSON.toJSONString(coverImages));
        wmNews.setEnable(true);

        // 从文章内容中获取所有的图片,构建到一个list集合中(文章内容中的图片)
        List<ImageDto> contextImageList = getImageFromContext(dto.getContent());

        if (dto.getType() == -1) { // 封面图片自动从文章内容获取
            int size = contextImageList.size();
            if (size == 0) {
                // 如果文章内容没有图片
                wmNews.setType(0);
                coverImages = contextImageList;
            } else if (size > 0 && size < 3) {
                // 如果文章内容少于3张图片
                wmNews.setType(1);
                coverImages = contextImageList.subList(0, 1); // 封面图片
            } else if (size >= 3) {
                // 如果文章内容等于或多于图片
                wmNews.setType(3);
                coverImages = contextImageList.subList(0, 3);
            }
            wmNews.setImages(JSON.toJSONString(coverImages));
        }
        this.saveOrUpdate(wmNews);// 如果有id就是update,没有就是save

        // 判断是否存为草稿 状态 提交为1  草稿为0
        if (dto.getStatus() == 1) {
            // 关联内容中的图片(contextImageList)与素材的关系
            saveRelation(contextImageList, wmNews.getId(), 0);
            // 关联封面图片(coverImages)与素材的关系
            saveRelation(coverImages, wmNews.getId(), 1);

            // 调用自媒体文章审核的方法
            auditService.audit(wmNews); // 这个方法比较耗时 1.阿里云文本审核 2.阿里云图片审核 3.feign远程调用保存APP文章
        }

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult upOrDown(WmNewsDto dto) {
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 1.先判断是否有文章id
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 2.再判断根据文章id是否能够查询出对象
        WmNews wmNews = this.getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 3.判断该自媒体文章是否为当前登录人发布
        if (user.getUserId().intValue() != wmNews.getUserId().intValue()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        // 4.判断文章是否为发布状态
        if (wmNews.getStatus() != 9) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_UP_DOWN);
        }
        wmNews.setEnable(dto.getEnable() == 1 ? true : false);
        this.updateById(wmNews);

        // 向Kafka中放消息
        Long articleId = wmNews.getArticleId();

        Map map = new HashMap();
        map.put("articleId",articleId);
        map.put("enable",dto.getEnable() == 1 ? true : false);

        kafkaTemplate.send(upDownTopic,JSON.toJSONString(map));
        log.info("上下架后向Kafka中放入数据");
        return ResponseResult.okResult();
    }

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Value("${topic.upDownTopic}")
    private String upDownTopic;

    private void saveRelation(List<ImageDto> imageDtoList, Integer newsId, int type) {
        int ord = 0;
        for (ImageDto imageDto : imageDtoList) {
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setMaterialId(imageDto.getId());
            wmNewsMaterial.setNewsId(newsId);
            wmNewsMaterial.setType(type);
            wmNewsMaterial.setOrd(ord);
            ord++;
            wmNewsMaterialService.save(wmNewsMaterial);
        }
    }

    private List<ImageDto> getImageFromContext(String content) {
        List<ContentDto> contentDtoList = JSON.parseArray(content, ContentDto.class);
        List<ImageDto> imageDtoList = new ArrayList<>();

        for (ContentDto contentDto : contentDtoList) {
            if (contentDto.getType().equals("image")) {
                ImageDto imageDto = new ImageDto();
                imageDto.setId(contentDto.getId());
                imageDto.setUrl(contentDto.getValue());
                imageDtoList.add(imageDto);
            }

        }
        return imageDtoList;
    }

    @Autowired
    private IWmNewsMaterialService wmNewsMaterialService;

    /**
     * 根据自媒体文章id删除文章与素材之间的关联关系
     *
     * @param newsId 自媒体文章id
     */
    private void deleteRelation(Integer newsId) {
        LambdaQueryWrapper<WmNewsMaterial> lqwWmNewsMaterial = new LambdaQueryWrapper<>();
        lqwWmNewsMaterial.eq(WmNewsMaterial::getNewsId, newsId);
        wmNewsMaterialService.remove(lqwWmNewsMaterial);
    }
}
